package builder;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * @author 赵希奥
 * @date 2022/3/16 12:39
 * @gitHub https://github.com/CKXGZXA
 * @gitee https://gitee.com/ckxgzxa
 * @description: 工具类
 */
public class XMLUtil {
    /**
     * 该方法用于从XML配置文件中提取具体类的类名, 并返回一个实例对象
     * @return
     */
    public static Object getBean() {
        try {
            // 创建 DOM 文档对象
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(new File("src//abstractfactory//config.xml"));

            // 获取包含类名的文本结点
            NodeList nl = doc.getElementsByTagName("className");
            Node classNode = nl.item(0).getFirstChild();
            String cName = classNode.getNodeValue();

            // 通过类名生成实例对象并将其返回
            Class<?> c = Class.forName(cName);
            return c.newInstance();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
